package com.htw.rv.fast_scroller.slide

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.ViewTreeObserver
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.htw.rv.fast_scroller.adapter.RvAdapter
import com.htw.rv.fast_scroller.databinding.ActivityFastScrollerSlideLetterBinding
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @author htw
 * createTime: 2022-05-10
 * desc: 字母索引
 */
class FastScrollerSlideLetterActivity : AppCompatActivity() {

    private lateinit var binding: ActivityFastScrollerSlideLetterBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityFastScrollerSlideLetterBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initRv()
        initRvLetter()

    }

    private fun initRv() {
        binding.rvContent.layoutManager = LinearLayoutManager(this)
        binding.rvContent.adapter = RvAdapter().apply {
            initListDataWithLetter()
        }
    }

    private fun initRvLetter() {
        binding.rvLetter.layoutManager = LinearLayoutManager(this)
        binding.rvLetter.adapter = SlideLetterAdapter().apply {
            initListData()
        }

        val tvLetterLocation = IntArray(2)
        binding.tvLetter.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                tvLetterLocation[0] = binding.tvLetter.width
                tvLetterLocation[1] = binding.tvLetter.height
                binding.tvLetter.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })

        binding.rvLetter.addOnItemTouchListener(object : RecyclerView.OnItemTouchListener {
            private var job: Job? = null
            override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
                return true
            }

            override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
                when (e.action) {
                    MotionEvent.ACTION_DOWN -> {
                        job?.cancel()
                        binding.tvLetter.isVisible = true
                    }
                    MotionEvent.ACTION_MOVE -> {
                        job?.cancel()
                        binding.tvLetter.isVisible = true
                    }
                    MotionEvent.ACTION_UP -> {
                        job = lifecycleScope.launch {
                            delay(500L)
                            binding.tvLetter.isVisible = false
                        }
                    }
                }
                rv.layoutManager?.let { layoutManager ->
                    val x = e.x
                    val y = e.y
                    val rawX = e.rawX
                    val rawY = e.rawY

                    val rvLetterLocation = IntArray(2)
                    rv.getLocationOnScreen(rvLetterLocation)

                    layoutManager as LinearLayoutManager
                    val firstPosition = layoutManager.findFirstVisibleItemPosition()
                    val lastPosition = layoutManager.findLastVisibleItemPosition()

                    val locationXY = IntArray(2)
                    var viewW: Int
                    var viewH: Int
                    var locationX: Int
                    var locationY: Int
                    var holder: SlideLetterAdapterVH?
                    for (position in firstPosition..lastPosition) {
                        val positionItemView = layoutManager.findViewByPosition(position)
                        if (positionItemView != null) {
                            viewW = positionItemView.width
                            viewH = positionItemView.height
                            positionItemView.getLocationOnScreen(locationXY)
                            locationX = locationXY[0]
                            locationY = locationXY[1]
                            Log.e(
                                "HTW",
                                "onTouchEvent -> ($x, $y), ($rawX, $rawY), $position, ($viewW, $viewH), ($locationX, $locationY)"
                            )

                            holder =
                                rv.findContainingViewHolder(positionItemView) as? SlideLetterAdapterVH

                            if (rawX >= locationX && rawX <= locationX + viewW && rawY >= locationY && rawY <= (locationY + viewH)) {
                                if(e.action == MotionEvent.ACTION_UP) {
                                    holder?.binding?.tvLetter?.setTextColor(Color.BLACK)
                                } else {
                                    holder?.binding?.tvLetter?.setTextColor(Color.GREEN)
                                }

                                val letterText = holder?.binding?.tvLetter?.text
                                binding.tvLetter.text = letterText
                                val tvLetterLayoutParam =
                                    binding.tvLetter.layoutParams as ConstraintLayout.LayoutParams
                                //tvLetterLayoutParam.topMargin = locationY + viewH/2 - rvLetterLocation[1] - tvLetterLocation[1]/2
                                tvLetterLayoutParam.topMargin =
                                    rawY.toInt() + viewH / 2 - rvLetterLocation[1] - tvLetterLocation[1] / 2
                                binding.tvLetter.layoutParams = tvLetterLayoutParam

                                if (letterText != null && letterText.isNotEmpty()) {
                                    val listData =
                                        (binding.rvContent.adapter as RvAdapter).getListData()
                                    listData.forEachIndexed { index, rvItemData ->
                                        if (rvItemData.name == letterText) {
                                            binding.rvContent.scrollToPosition(index)
                                        }
                                    }
                                }

                            } else {
                                holder?.binding?.tvLetter?.setTextColor(Color.BLACK)
                            }
                        }
                    }

                }
            }

            override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
            }

        })
    }
}